package com.wash.shoes.controller.mobile;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.util.StrUtil;
import com.lop.open.api.sdk.internal.fastjson.JSONObject;
import com.ruoyi.common.core.domain.R;
import com.wash.shoes.domain.dto.WxMiniCodeDto;
import com.wash.shoes.domain.wx.WxQrCodeComponent;
import com.wash.shoes.entity.CustomerPo;
import com.wash.shoes.entity.RegionCustomerPo;
import com.wash.shoes.entity.RegionDistributorPo;
import com.wash.shoes.exception.WashException;
import com.wash.shoes.service.CustomerService;
import com.wash.shoes.service.OrderService;
import com.wash.shoes.service.RegionCustomerService;
import com.wash.shoes.service.RegionDistributorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author lijianguo
 * @Date 29/11/2024 21:28
 * 请输入类的简介
 **/
@Log4j2
@Api(tags = {"移动端-登录"})
@RestController
@RequestMapping({"/mobile-api/customer"})
public class WxAuthMController extends BaseMController {

    @Resource
    private WxMaService wxMaService;

    @Resource
    private CustomerService customerService;

    @Resource
    private OrderService orderService;

    @Resource
    RegionDistributorService regionDistributorService;

    @Resource
    RegionCustomerService regionCustomerService;

    @Resource
    WxQrCodeComponent wxQrCodeComponent;

    @ApiOperation("用户注册登录")
    @PostMapping("/registerPhone")
    @Transactional
    public R<CustomerPo> registerPhone(@RequestBody WxMiniCodeDto wxMiniCodeDto) throws WxErrorException {

        // 查询用户信息
        WxMaJscode2SessionResult wxMaJsCode = wxMaService.getUserService().getSessionInfo(wxMiniCodeDto.getCode());
        // 打印日志
        log.info("registerPhone is {} ", JSONObject.toJSONString(wxMaJsCode));
        // 获取用户信息
        CustomerPo customerPo = customerService.getByOpenId(wxMaJsCode.getOpenid());
        if (customerPo != null) {
            return R.ok(customerPo);
        }
        // 如果用户不存在,且没有传电话过来,就是说这个数据不对,需要重新注册
        if (StrUtil.isBlankIfStr(wxMiniCodeDto.getPhone())) {
            return R.ok(null);
        }

        // 绑定号码
        customerPo = customerService.getByPhone(wxMiniCodeDto.getPhone());
        if (customerPo != null) {
            customerPo.setOpenId(wxMaJsCode.getOpenid());
            customerService.updateById(customerPo);
            return R.ok(customerPo);
        }
        // 新增用户
        customerPo = new CustomerPo();
        customerPo.setPhone(wxMiniCodeDto.getPhone());
        customerPo.setOpenId(wxMaJsCode.getOpenid());
        // 设置推广的人数, os_customer
        if (StrUtil.isNotBlank(wxMiniCodeDto.getInviteCusId())) {
            RegionDistributorPo regionDistributorPo = regionDistributorService.getByUserId(wxMiniCodeDto.getInviteCusId());
            // 设置推广的人数, 只有区域经理 状态为起用的才有
            if (regionDistributorPo != null && 1 == regionDistributorPo.getStatus()) {
                regionDistributorPo.setPromotionNum(regionDistributorPo.getPromotionNum() + 1);
                regionDistributorService.updateById(regionDistributorPo);
                customerPo.setInviteCusId(wxMiniCodeDto.getInviteCusId());
            }
        }

        customerPo.setName("微信用户");
        customerService.saveOrUpdate(customerPo);
        // 已经有推广的信息了,推广用户的日志
        if (StrUtil.isNotBlank(customerPo.getInviteCusId())) {
            RegionCustomerPo regionCustomerPo = new RegionCustomerPo();
            regionCustomerPo.setCustomerId(customerPo.getId());
            regionCustomerPo.setRecommendId(customerPo.getInviteCusId());
            regionCustomerService.save(regionCustomerPo);
        }
        //设置用户的id
        orderService.updateOrderToUser(wxMiniCodeDto.getPhone(), customerPo.getId());

        return R.ok(customerPo);
    }

    @ApiOperation("获取手机号码")
    @PostMapping("/getUserPhone")
    public R<WxMaPhoneNumberInfo> getUserPhone(@RequestBody WxMiniCodeDto wxMiniCodeDto) throws WxErrorException {
        // 查询code
        log.info("getUserPhone is {} ", JSONObject.toJSONString(wxMiniCodeDto));
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(wxMiniCodeDto.getCode());
        return R.ok(phoneNoInfo);
    }

    @ApiOperation("设置用户的推荐人")
    @GetMapping("/setInvitedUser")
    public R<CustomerPo> setInvitedUser(String customerId, String invitedUserId) {
        // 查询code
        log.info("setInvitedUser is {} {}", customerId, invitedUserId);
        CustomerPo customerPo = customerService.getById(customerId);
        if (customerPo == null) {
            throw new WashException("用户不存在");
        }
        if (StrUtil.isNotBlank(customerPo.getInviteCusId())) {
            throw new WashException("已经绑定了推广人,请勿重新绑定");
        }
        // 设置区域代理
        RegionDistributorPo regionDistributorPo = regionDistributorService.getByUserId(invitedUserId);
        // 设置推广的人数, 只有区域经理 状态为起用的才有
        if (regionDistributorPo != null && 1 == regionDistributorPo.getStatus()) {
            regionDistributorPo.setPromotionNum(regionDistributorPo.getPromotionNum() + 1);
            regionDistributorService.updateById(regionDistributorPo);
            customerPo.setInviteCusId(invitedUserId);
            // 推广的历史记录
            RegionCustomerPo regionCustomerPo = new RegionCustomerPo();
            regionCustomerPo.setCustomerId(customerPo.getId());
            regionCustomerPo.setRecommendId(customerPo.getInviteCusId());
            regionCustomerService.save(regionCustomerPo);
        }
        customerService.saveOrUpdate(customerPo);
        return R.ok(customerPo);
    }

    @ApiOperation("获取推荐的二维码")
    @GetMapping("/getQr")
    public R<String> getQr(String path) {
        // 查询code
        return R.ok(wxQrCodeComponent.getQrCode(path));
    }
}
